var express = require('express');
var router = express.Router();
var { Users, Mvs } = require('../utils/model');
var { startEncrypt, getDecrypt, checkSession} = require("../utils/index");

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

//注册路由
router.post('/register', function (req, res, next) {
  var body = req.body;
  var username = body.username;
  var password = body.password;
  var time = new Date();
  // console.log(username,password);
  if (username && password) {
    Users.findOne({
      name: username
    }).then(result => {
      if (result) {
        res.send("<script>alert('用户名已经被注册，请重新注册');location.href='/register'</script>")
      } else {
        Users.insertMany({
          name: username,
          password: password,
          time: time
        }).then(data => {
          res.send(`<script>alert('注册成功，马上前往登录');location.href='/login?username=${startEncrypt(username)}'</script>`)
        })
      }
    })
  } else {
    res.send("<script>alert('用户名或者密码是必填字段，请重新填写');location.href='/register'</script>")
  }
})


//登录路由
router.post('/login', function (req, res, next) {
  var body = req.body;
  var username = body.username;
  var password = body.password;
  if (username&&password) {
    Users.findOne({
      name: username
    }).then(result => {
      if (result) {
        if (result.password == password) {
          req.session.username = result.name;
          req.session.logintime = new Date();
          req.session.token = startEncrypt(result.name);  //判断用户是否登录
          res.redirect("/home");  //登录成功 跳转首页 重定向
        } else {
          res.send("<script>alert('用户名或者密码错误，请重新登录');location.href='/login'</script>")
        }
      } else {
        res.send("<script>alert('用户名不存在,请重新登录');location.href='/login'</script>")
      }
    })
  }else{
    res.send("<script>alert('用户名或者密码是必填字段,请重新填写');location.href='/login'</script>")
  }
})

//修改密码路由
router.post("/changepass",(req,res)=>{
  checkSession(req,res,()=>{
    var body = req.body;
    Users.findOne({
      name:body.username,
    }).then(data=>{
      if(data){
        if(data.password == body.oldpass){
          Users.updateMany({
            name:body.username,
          },{
            $set:{
              password:body.newpass
            }
          }).then(result=>{
            res.json({
              code:200,
              type:1,
              msg:"密码修改成功....."
            })
          })
        }else{
          res.json({
            code:200,
            type:0,
            msg:"旧密码不正确....."
          })
        }
      }else{
        res.json({
          code:200,
          type:0,
          msg:"用户名不存在....."
        })
      }
    })
  })
})

module.exports = router;
